/**
 * @Title: index
 * @Package mall-fe
 * @author Shinelon
 * @date 2017/9/6 21:25
 * @version V1.0
 * @desc START
 */
'use strict';
require('./index.css');
require('js/common/nav/index.js');
require('js/common/header/index.js');
var navSide         = require('js/common/nav-side/index.js');
var shiqla             = require('util/shiqlamall');
var userService           = require('service/user-service.js');
var templateIndex   = require('./template.string');

// page 逻辑部分
var page = {
    init: function(){
        this.onLoad();
        this.bindEvent();
    },
    onLoad : function(){
        // 初始化左侧菜单
        navSide.init({
            name: 'user-center'
        });
        // 加载用户信息
        this.loadUserInfo();
    },
    // 加载用户信息
    loadUserInfo : function(){
        var userHtml = '';
        userService.getUserInfo(function(res){
            userHtml = shiqla.renderHtml(templateIndex, res);
            $('.panel-body').html(userHtml);
        }, function(errMsg){
            window.location.href = './result.html?type=getUserInfo';
        });
    },
    bindEvent:function () {
        var _this = this;
        $(document).on('click','.btn-submit',function () {
           var userInfo = {
               phone:$.trim($('#phone').val()),
               email:$.trim($('#email').val()),
               question:$.trim($('#question').val()),
               answer:$.trim($('#answer').val())
           };
           var validateResult  = _this.validateForm(userInfo);
           if(validateResult.status){
               userService.updateUserInfo(userInfo,function (result,msg) {
                   // shiqla.successTips(result);
                   window.location.href='./user-center.html';
               },function (errMsg) {
                   shiqla.errorTips(errMsg);
               })
           }else{}
            shiqla.errorTips(validateResult.msg);
        });
    },
    validateForm:function(formData){
        var result = {
            status: false,
            msg:''
        };
        if(!shiqla.validate(formData.phone,'phone')){
            result.msg = '手机格式不正确';
            return result;
        }
        if(!shiqla.validate(formData.email,'email')){
            result.msg = '邮箱地址不正确';
            return result;
        }
        if(!shiqla.validate(formData.question,'require')){
            result.msg = '提示问题不能为空';
            return result;
        }
        if(!shiqla.validate(formData.answer,'require')){
            result.msg = '提示问题答案不能为空';
            return result;
        }
        //通过验证,返回正确数据
        result.status = true;
        result.msg = '验证通过';
        return result;
    }

};
$(function(){
    page.init();
});